import React, { Component } from "react";
import { Table } from "antd";
import AddActivityForm from "./forms/addActivityForms";
import { addActivity, activityList, editActivity, delActivity,uploadImg } from "../../api/activity";

import EditForm from "./forms/editorForms";
import { Button, Divider, message, Card } from "antd";

const { Column } = Table;

class Activity extends Component {
    _isMounted = false; // 这个变量是用来标志当前组件是否挂载
    state = {
        list: [],
        array: [],
        addActivityModalVisible: false,
        addActivityModalLoading: false,
        loading: false,
        total: 0,
        listQuery: {
            pageNumber: 1,
            pageSize: 10,
            title: "",
            status: "",
        },
        editModalVisible: false,
        editModalLoading: false,
        currentRowData: {
            activityId: 0,
            activityTime: "",
            activitySpot: "",
            activityImg: "",
            activityContent: "",
            fullTitle: "",
            shortTitle: "",
        },
        
    };

    fetchData = () => {
        this.setState({ loading: true });
        activityList().then((response) => {
            console.log(this.state.array);
            console.log("response",response)
            this.setState({ loading: false});
            let list = response;
            console.log("list:",list)
            for (var i = 0; i < list.length; i++) {
                if (list[i].shopContent) {
                    list[i].shopContent = list[i].shopContent.slice(0, 40) + "......";
                }
            }
            console.log(list);
            const total = response.length;
            if (this._isMounted) {
                console.log("执行了修改状态前一行")
                console.log(response)
                this.setState({ list, total});
            }
        });
    };

    componentDidMount() {
        this._isMounted = true;
        activityList().then((response) => {
            console.log("responsecomponentDidMount",response)
            this.setState({ array: response });
        });
        this.fetchData();
    }
    componentWillUnmount() {
        this._isMounted = false;
    }

    handleDelete = (row) => {
        // console.log(row);
        // console.log(row.activityId);
        delActivity(row.activityId).then((res) => {
            message.success("删除成功");
            this.fetchData();
            console.log(res);
        });
    };
    handleEdit = (row) => {
        console.log(row);
        console.log(this.state.array);
        const currentList = this.state.array.filter((obj) => obj.activityId == row.activityId);
        // console.log(currentList[0]);
        this.setState({
            currentRowData: Object.assign({}, currentList[0]),
            editModalVisible: true,
        });
        console.log(this.state.currentRowData);
    };

    handleOk = (state,setFieldsValue) => {
        
        const { form } = this.formRef.props;
        
        form.validateFields((err, fieldsValue) => {
            if (err) {
                return;
            }
            if (fieldsValue.activityImg==this.state.currentRowData.activityImg) {
                const values = {
                    ...fieldsValue,
                    activityTime: fieldsValue["activityTime"],
                };
                console.log(fieldsValue["activityTime"]);
                this.setState({ editModalLoading: true });
                console.log(values);
                editActivity(values)
                    .then((response) => {
                        form.resetFields();
                        this.setState({ editModalVisible: false, editModalLoading: false });
                        message.success("编辑成功!");
                        this.fetchData();
                    })
                    .catch((e) => {
                        message.success("编辑失败,请重试!");
                    });
            }
            else{
                let data = new FormData();
                data.set('img',state.file);
                uploadImg(data)
                .then(r=> r.text() )
                .then(res => {
                    console.log(res)
                    setFieldsValue({
                        activityImg: res,
                    });
                    form.validateFields((e,v)=>{
                        if (e) {
                            return;
                        }
                        const myvalues = {
                            ...v,
                            activityTime: fieldsValue["activityTime"],
                        };
                        console.log(myvalues);
                        this.setState({
                            editModalLoading: true,
                        });
                        console.log(data.get('img'))
                        editActivity(myvalues)
                        .then((response) => {
                            form.resetFields();
                            this.setState({ editModalVisible: false, editModalLoading: false });
                            message.success("编辑成功!");
                            this.fetchData();
                        })
                        .catch((e) => {
                            message.error("编辑失败,请重试!");
                        });
                    })
                        
                    
                    
                })
                .catch(e => {
                    console.log(e)
                    message.error("添加失败,请重试!");
                    this.setState({
                        addActivityModalLoading: false
                    });
                })
                
            }
        });
    };

    handleAddActivity = (row) => {
        this.setState({
            addActivityModalVisible: true,
        });
    };
    handleAddActivityOk = (state,setFieldsValue) => {
        const { form } = this.addActivityFormRef.props;
        console.log(state);
        let data = new FormData();
        data.set('img',state.file);
        console.log("-------------------------------");
        console.log("this:",this)
        console.log("this.formRef:",this.formRef)//---------------------被编辑
        form.validateFields((err,val)=>{
            console.log(val);
            if (val.activityImg!=undefined) {
                uploadImg(data)
                .then(r=> r.text() )
                .then(res => {
                    console.log(res)
                    setFieldsValue({
                        activityImg: res,
                    });
                    form.validateFields((err, values) => {
                        console.log(values);
                        if (err) {
                            return;
                        }
                        this.setState({
                            addActivityModalLoading: true,
                        });
                        console.log(data.get('img'))
                        addActivity(values)
                            .then((response) => {
                                console.log(response);
                                form.resetFields();
                                this.setState({
                                    addActivityModalVisible: false,
                                    addActivityModalLoading: false,
                                });
                                message.success("添加成功!");
                                this.fetchData();
                                // this.getUsers();
                            })
                            .catch((e) => {
                                console.log(e);
                                message.error("添加失败,请重试!");
                            });
                        
                    });
                    
                })
                .catch(e => {
                    console.log(e)
                    message.error("添加失败,请重试!");
                    this.setState({
                        addActivityModalLoading: false
                    });
                })
            }
            else{
                addActivity(val)
                .then((response) => {
                    console.log(response);
                    form.resetFields();
                    this.setState({
                        addActivityModalVisible: false,
                        addActivityModalLoading: false,
                    });
                    message.success("添加成功!");
                    this.fetchData();
                    // this.getUsers();
                })
                .catch((e) => {
                    console.log(e);
                    message.error("添加失败,请重试!");
                });
            }
        })
        this.fetchData();
        
    };
    handleCancel = (_) => {
        this.setState({
            editModalVisible: false,
            addActivityModalVisible: false,
        });
    };
    render() {
        const title = (
            <span>
                <Button type="primary" onClick={this.handleAddActivity}>
                    添加商品
                </Button>
            </span>
        );
        return (
            <div className="app-container">
                <Card title={title}>
                    <Table
                        bordered
                        rowKey={(record, index) => index}
                        dataSource={this.state.list}
                        loading={this.state.downloadLoading}
                        pagination={{
                            total: this.state.total,
                            showTotal: (total) => `共${total}条数据`,
                        }}
                        scroll={{ y: 480 }}
                    >
                        <Column
                            title="商品id"
                            dataIndex="activityId"
                            key="activityId"
                            width={70}
                            align="center"
                            sorter={(a, b) => a.activityId - b.activityId}
                            defaultSortOrder="descend"
                        />
                        <Column
                            title="商家名称"
                            dataIndex="shortTitle"
                            key="shortTitle"
                            width={150}
                            align="center"
                        />
                        {/* <Column
                            title="活动全称"
                            dataIndex="fullTitle"
                            key="fullTitle"
                            width={100}
                            align="center"
                        />
                        <Column
                            title="活动时间"
                            dataIndex="activityTime"
                            key="activityTime"
                            width={120}
                            align="center"
                        />
                        <Column
                            title="活动地点"
                            dataIndex="activitySpot"
                            key="activitySpott"
                            width={120}
                            align="center"
                        /> */}
                        <Column
                            title="商品图片"
                            dataIndex="activityImg"
                            key="activityImg"
                            width={150}
                            align="center"
                        />
                        <Column
                            title="商家介绍"
                            dataIndex="shopContent"
                            key="shopContent"
                            width={160}
                            align="center"
                        />
                        <Column
                            title="操作"
                            key="action"
                            width={120}
                            align="center"
                            render={(text, row) => (
                                <span>
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        icon="edit"
                                        title="编辑"
                                        onClick={this.handleEdit.bind(null, row)}
                                    />
                                    <Divider type="vertical" />
                                    <Button
                                        type="primary"
                                        shape="circle"
                                        icon="delete"
                                        title="删除"
                                        onClick={this.handleDelete.bind(null, row)}
                                    />
                                </span>
                            )}
                        />
                    </Table>
                </Card>
                <br />
                <EditForm
                    currentRowData={this.state.currentRowData}
                    wrappedComponentRef={(formRef) => (this.formRef = formRef)}
                    visible={this.state.editModalVisible}
                    confirmLoading={this.state.editModalLoading}
                    onCancel={this.handleCancel}
                    onOk={this.handleOk}
                />
                <AddActivityForm
                    wrappedComponentRef={(formRef) => (this.addActivityFormRef = formRef)}
                    visible={this.state.addActivityModalVisible}
                    confirmLoading={this.state.addActivityModalLoading}
                    onCancel={this.handleCancel}
                    onOk={this.handleAddActivityOk}
                />
            </div>
        );
    }
}

export default Activity;
